import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './core/filter/http-exception/http-exception.filter'; //全局错误的过滤器
import { TransformInterceptor } from './core/interceptor/transform/transform.interceptor';//全局注册拦截器
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; // 生成接口UI文档
import { JwtAuthGuard } from './modules/auth/auth.guard'; //全局守卫
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.setGlobalPrefix('api/'); // 设置全局路由前缀
  
  // app.enableCors({
  //   origin: 'http://localhost:5173', // 允许前端地址访问
  //   credentials: true,               // 允许携带 cookie 或 token
  // });

  // 注册全局错误的过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  // 全局注册拦截器
  app.useGlobalInterceptors(new TransformInterceptor())

  // 全局 JWT 守卫
  const reflector = app.get(Reflector);
  app.useGlobalGuards(new JwtAuthGuard(reflector));

  //参数类型自动转换
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 👈 开启自动类型转换
    }),
  );
  
  const config = new DocumentBuilder()
    .setTitle('用户接口')
    .setDescription('用户管理接口文档')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(process.env.PORT ?? 3000, '0.0.0.0');

  // ✅ 启动信息输出
  const baseUrl = `http://localhost:${process.env.PORT ?? 3000}`;
  console.log(`\n✅ 服务启动成功: ${baseUrl}`);
  console.log(`📚 Swagger 文档: ${baseUrl}/api\n`);
}
bootstrap();
